package org.cboard.security.service;

import java.util.ArrayList;

import org.apache.shiro.SecurityUtils;
import org.cboard.controller.LoginController;
import org.cboard.dto.User;
import org.cboard.services.AuthenticationService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

/**
 * Created by yfyuan on 2016/12/14.
 */
@Service
public class DbAuthenticationService implements AuthenticationService {


    @Value("${anonymous.id}")
    private String userid;
    @Value("${anonymous.username}")
    private String username;
    @Value("${anonymous.password}")
    private String password;


    @Override
    public User getCurrentUser() {
//        SecurityContext context = SecurityContextHolder.getContext();
//        if (context == null) {
//            return null;
//        }
//        Authentication authentication = context.getAuthentication();
//        if (authentication == null) {
//            return null;
//        }
//        Object user = authentication.getPrincipal();
//        if (user == null) {
//            return null;
//        } else if (user instanceof User) {
//            return (User) user;
//        }
	User sessionUser =(User) SecurityUtils.getSubject().getSession().getAttribute(LoginController.SESSION_LOGIN_USER);
	if(sessionUser==null){
	    return getAnonymousUser();
	}
	return sessionUser;
    }


    public User getAnonymousUser() {

        User user = new User(username, password, new ArrayList<GrantedAuthority>());
        user.setUserId(userid);
        return user;
    }
}
